package com.itbaizhan;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**根据用户名称模糊查找用户信息*/
public class FuzzyQueryTest {
    //返回一个集合，ORM编程思想

    public List<Users> fuzzyQuery(String username){
        List<Users> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            connection = JdbcUtils.getConnection();
            //%在实例化时才给，因为查询时%可能在前面，也可能在后面
            ps = connection.prepareStatement("select * from users where username like ?");
            //绑定参数
            ps.setString(1,username);
            //执行sql
            rs = ps.executeQuery();
            while (rs.next()){
                Users users = new Users();
                 users.setUserid(rs.getInt("userid"));
                 users.setUsername(rs.getString("username"));
                 users.setUsergae(rs.getInt("userage"));
                //将信息添加到集合
                list.add(users);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResource(rs,ps,connection);
        }
        return list;
    }

    public static void main(String[] args) {
        FuzzyQueryTest fq = new FuzzyQueryTest();
        //得到的结果是集合
        List<Users> list = fq.fuzzyQuery("%a%");
        for(Users u:list){
            System.out.println(u.getUserid()+" "+u.getUsername()+" "+ u.getUsergae());
        }
    }
}
